package com.adcok.lcdns.activity.ad;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.adcok.lcdns.cronos.http.CNLottoAdApiSet;
import com.adcok.lcdns.util.LottoAdImageDownloaderFile;
import com.adcok.lcdns.util.LottoAdOverButton;
import com.adcok.lcdns.R;

public class LottoAdDetailActivity extends Activity {
	
	private Button mCallButton;
	private ImageView mAdImage;
	private ProgressBar mProgressBar;
	
	private String mAdPhoneNumber = "";
	private String mAdImagePath = "";
	
	private Context mContext;
	
	private LottoAdImageDownloaderFile mImageDownloader;
	
	private AsyncTask<Void, Void, Void> mTask, mDelayTask;
	
	private boolean mIsCallButtonShown = false;
	
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.lottoad_detail_activity);
		mContext = this;
		Bundle extras = getIntent().getExtras();
		
		mAdPhoneNumber = extras.getString("adPhoneNumber");
		mAdImagePath = extras.getString("originImage");
		if(!CNLottoAdApiSet.isLive()) {
			Log.i("BenTag", "extra phone number : " + mAdPhoneNumber + ", origin path : " + mAdImagePath);
		}
		
		mImageDownloader = new LottoAdImageDownloaderFile(this);
		
		
		initViews();
		
		showCallButtonWithGivenTime(true, 3000, 3000);
		
	}
	
	private void initViews() {
		mCallButton = (Button) findViewById(R.id.btn_lottoad_detail_call);
		mCallButton.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Drawable getBackground = v.getBackground();
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					v.setBackgroundDrawable(LottoAdOverButton.grayimg(getBackground));
				}
				else if(event.getAction() == MotionEvent.ACTION_UP){
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					
					if(mAdPhoneNumber != null && !mAdPhoneNumber.equals("")) {
						// 전화연결 클릭시 페이지에 해당하는 전화번호로 바로 통화연결.
//						Toast.makeText(mContext, "Current page index : " + mPage + ", Selected Phone number : " + mPhoneNumberArr.get(mPage), Toast.LENGTH_SHORT).show();
						try {
							startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mAdPhoneNumber)));
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						showPhoneNumberErrorDialog();
					}
					
				}
				return false;
			}
		});
		
		
		
		mAdImage = (ImageView) findViewById(R.id.iv_lottoad_detail_image);
		mAdImage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				if(mIsCallButtonShown) {
					showCallButtonWithGivenTime(false, 0, 0);
				} else {
					showCallButtonWithGivenTime(true, 0, 0);
				}
				
			}
		});
		
		mProgressBar = (ProgressBar) findViewById(R.id.pb_lottoad_detail_progress);
		
		updateUI();
	}
	
	
	/*
	 * @param show : 전화버튼을 보여줄지 여부
	 * @param time : 일정 시간만 보여줘야하는 경우 보여줄 시간(show가 true일 때만 동작하고 이외에는 무시함. 계속 보여주는 경우에는 0)
	 * @param delay : 일정 시간 후 버튼을 나타내고 싶을 때 지정(일반적으로는 0)
	 * 
	 * */
	private void showCallButtonWithGivenTime(boolean show, final long time, long delay) {
		if(show) {
			if(time == 0) {
				if(mTask != null) {
					if(mTask.getStatus() == AsyncTask.Status.RUNNING || mTask.getStatus() == AsyncTask.Status.PENDING) {
						mTask.cancel(true);
					}
					mTask = null;
				}
				
				if(mDelayTask != null) {
					if(mDelayTask.getStatus() == AsyncTask.Status.RUNNING || mDelayTask.getStatus() == AsyncTask.Status.PENDING) {
						mDelayTask.cancel(true);
					}
					mDelayTask = null;
				}
				
				showCallButton(true);
				
			} else {
				if(delay != 0) {
					runDelayTask(time, delay);
				} else {
					runTask(time);
				}
				
			}
			
		} else {
			showCallButton(false);
		}
	}
	
	private void runDelayTask(final long time, final long delay) {
		mDelayTask = new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				try {
					Thread.sleep(delay);
				} catch(InterruptedException e) {
					e.printStackTrace();
				}
				return null;
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				runTask(time);
			}
			
		}.execute();
	}
	
	private void runTask(final long time) {
		mTask = new AsyncTask<Void, Void, Void>() {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showCallButton(true);
				
			}
			
			@Override
			protected Void doInBackground(Void... params) {
				try {
					Thread.sleep(time);
				} catch(InterruptedException e) {
					e.printStackTrace();
				}
				return null;
				
			}
			
			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				showCallButton(false);
			}
			
		}.execute();
		
		
	}
	
	private void showPhoneNumberErrorDialog() {
		Toast.makeText(this, "전화번호를 가져오는데 실패했습니다.", Toast.LENGTH_SHORT).show();
	}
	
	
	private void recycleBitmap(ImageView iv) {
		if(iv != null) {
			try {
				Drawable d = iv.getDrawable();
				if(d instanceof BitmapDrawable) {
					Bitmap b = ((BitmapDrawable)d).getBitmap();
					b.recycle();
				}
				
				d.setCallback(null);
			} catch(Exception e) {
				e.getStackTrace();
			}
		}
	}
	
	private void updateUI(){
		recycleBitmap(mAdImage);
		mImageDownloader.download(mAdImagePath, mAdImage, mProgressBar);
		
	}
	
	private void showCallButton(boolean isShown) {
		if(isShown) {
			mIsCallButtonShown = true;
			mCallButton.setVisibility(View.VISIBLE);
		} else {
			mIsCallButtonShown = false;
			mCallButton.setVisibility(View.GONE);
		}
	}
	
	
	
}
